package grape.wx.rest.mp.basic.mvc;

import grape.common.exception.runtime.RDataNotExistException;
import grape.common.rest.mvc.SuperController;
import grape.wx.rest.mp.basic.form.WxMpTemplateIndustrySetForm;
import grape.wx.rest.mp.basic.mapper.MpConfigWebMapper;
import grape.wx.rest.mp.basic.vo.MpTempMsgIndustryDictGroupVo;
import grape.wx.rest.mp.basic.vo.WxMpTemplateIndustryVo;
import grape.wx.service.mp.MpProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateIndustry;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateIndustryEnum;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by yangwei
 * Created at 2020/7/20 20:48
 */
@RestController
@RequestMapping("/wx/mp/tempmsg")
@Api(tags = "公众号jsapi相关接口")
public class MpTemplateMessageController extends SuperController {

    @Autowired
    private WxMpService wxMpService;

    /**
     * 设置所属行业接口
     * @return
     */
    @ApiOperation("设置所属行业接口")
    @ResponseStatus(HttpStatus.CREATED)
    @PreAuthorize("hasAuthority('wx:mp:tempmsg:setIndustry')")
    @PostMapping("/{appId}/industry")
    public Boolean setIndustry(@PathVariable String appId,@RequestBody WxMpTemplateIndustrySetForm form) throws WxErrorException {
        WxMpTemplateIndustry wxMpIndustry = new WxMpTemplateIndustry();
        wxMpIndustry.setPrimaryIndustry(WxMpTemplateIndustryEnum.findByCode(form.getPrimaryIndustry()));
        wxMpIndustry.setSecondIndustry(WxMpTemplateIndustryEnum.findByCode(form.getSecondIndustry()));
        boolean b = wxMpService.switchoverTo(appId).getTemplateMsgService().setIndustry(wxMpIndustry);
        return b;
    }
    /**
     * 获取设置的行业信息
     * @return
     */
    @ApiOperation("获取设置的行业信息接口")
    @ResponseStatus(HttpStatus.OK)
    @PreAuthorize("hasAuthority('wx:mp:tempmsg:getIndustry')")
    @GetMapping("/{appId}/industry")
    public WxMpTemplateIndustryVo getIndustry(@PathVariable String appId) throws WxErrorException {
        WxMpTemplateIndustry templateIndustry = wxMpService.switchoverTo(appId).getTemplateMsgService().getIndustry();
        if (templateIndustry != null) {
            WxMpTemplateIndustryVo wxMpTemplateIndustryVo = new WxMpTemplateIndustryVo();
            wxMpTemplateIndustryVo.setPrimaryIndustry(templateIndustry.getPrimaryIndustry().getCode());
            wxMpTemplateIndustryVo.setPrimaryIndustryName(templateIndustry.getPrimaryIndustry().getSecondClass());
            wxMpTemplateIndustryVo.setPrimaryIndustryClass(templateIndustry.getPrimaryIndustry().getFirstClass());

            wxMpTemplateIndustryVo.setSecondIndustry(templateIndustry.getSecondIndustry().getCode());
            wxMpTemplateIndustryVo.setSecondIndustryName(templateIndustry.getSecondIndustry().getSecondClass());
            wxMpTemplateIndustryVo.setSecondIndustryClass(templateIndustry.getSecondIndustry().getFirstClass());
            return  wxMpTemplateIndustryVo;
        }
        throw new RDataNotExistException("行业数据不存在");
    }

    /**
     * 从行业模板库选择模板到帐号后台
     * @return
     */
    @ApiOperation("从行业模板库选择模板到帐号后台接口")
    @ResponseStatus(HttpStatus.CREATED)
    @PreAuthorize("hasAuthority('wx:mp:tempmsg:addTemplate')")
    @PostMapping("/{appId}/addTemplate/{shortTemplateId}")
    public String addTemplate(@PathVariable String appId,@PathVariable String shortTemplateId) throws WxErrorException {
        String s = wxMpService.switchoverTo(appId).getTemplateMsgService().addTemplate(shortTemplateId);
        return s;
    }

    /**
     * 获取模板列表接口
     * @return
     */
    @ApiOperation("获取模板列表接口")
    @ResponseStatus(HttpStatus.OK)
    @PreAuthorize("hasAuthority('wx:mp:tempmsg:templateList')")
    @GetMapping("/{appId}/templateList")
    public List<WxMpTemplate> getAllPrivateTemplate(@PathVariable String appId) throws WxErrorException {
        return wxMpService.switchoverTo(appId).getTemplateMsgService().getAllPrivateTemplate();
    }

    /**
     * 删除模板接口
     * @return
     */
    @ApiOperation("删除模板接口")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    @PreAuthorize("hasAuthority('wx:mp:tempmsg:deleteTemplate')")
    @DeleteMapping("/{appId}/deleteTemplate/{templateId}")
    public Boolean getAllPrivateTemplate(@PathVariable String appId,@PathVariable String templateId) throws WxErrorException {
        boolean b = wxMpService.switchoverTo(appId).getTemplateMsgService().delPrivateTemplate(templateId);
        return b;
    }
    /**
     * 发送模板消息接口
     * @return
     */
    @ApiOperation("发送模板消息接口")
    @ResponseStatus(HttpStatus.CREATED)
    @PreAuthorize("hasAuthority('wx:mp:tempmsg:sendTemplateMsg')")
    @PostMapping("/{appId}/sendTemplateMsg")
    public String sendTemplateMsg(@PathVariable String appId,@RequestBody WxMpTemplateMessage templateMessage) throws WxErrorException {
        String s = wxMpService.switchoverTo(appId).getTemplateMsgService().sendTemplateMsg(templateMessage);
        return s;
    }

    /**
     * 行业字典接口
     * @return
     */
    @ApiOperation("行业字典接口")
    @ResponseStatus(HttpStatus.OK)
    @GetMapping("/industryDict")
    public List<MpTempMsgIndustryDictGroupVo> industryDict() throws WxErrorException {
        List<MpTempMsgIndustryDictGroupVo> result = new ArrayList<>();

        MpTempMsgIndustryDictGroupVo mpTempMsgIndustryDictGroupVo = null;
        List<MpTempMsgIndustryDictGroupVo.MpTempMsgIndustryDictItemVo> items = null;
        MpTempMsgIndustryDictGroupVo.MpTempMsgIndustryDictItemVo dictItem = null;
        for (WxMpTemplateIndustryEnum value : WxMpTemplateIndustryEnum.values()) {
            mpTempMsgIndustryDictGroupVo = result.stream().filter(item -> isEqual(value.getFirstClass(), item.getName())).findFirst().orElse(null);

            if (mpTempMsgIndustryDictGroupVo == null) {
                mpTempMsgIndustryDictGroupVo = new MpTempMsgIndustryDictGroupVo();
                mpTempMsgIndustryDictGroupVo.setName(value.getFirstClass());
                result.add(mpTempMsgIndustryDictGroupVo);
            }
            items = mpTempMsgIndustryDictGroupVo.getItems();
            if (items == null) {
                items = new ArrayList<>();
                mpTempMsgIndustryDictGroupVo.setItems(items);
            }
            dictItem = items.stream().filter(item -> isEqual(item.getId(), value.getCode().toString())).findFirst().orElse(null);
            if (dictItem == null) {
                dictItem = new  MpTempMsgIndustryDictGroupVo.MpTempMsgIndustryDictItemVo();
                dictItem.setId(value.getCode().toString());
                dictItem.setName(value.getSecondClass());
                items.add(dictItem);
            }
        }
        return result;
    }

}
